<template>
  <page-layout :avatar="currUser.avatar">
    <div slot="headerContent">
      <div class="title">{{ welcome.timeFix[lang] }}，{{ currUser.name }}{{ welcome.message[lang] }}</div>
      <div>{{ currUser.position[lang] }}</div>
    </div>
    <template slot="extra">
      <head-info class="split-right" title="订单量（笔）" :content="OrderNum"/>
      <head-info class="split-right" title="商品数" :content="QuantityOfCommodity"/>
      <head-info class="split-right" title="访问量" :content="PageView"/>
      <head-info class="split-right" title="销售金额(元)" :content="total"/>
    </template>
    <template>
      <div class="dataCont">
        <a-card title="待办事项" class="dataCont-left">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-card :bordered="false" style="text-align: center;">
                <a-statistic title="待发货" v-model="GoodsWaitingToBeSent"/>
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card :bordered="false" style="text-align: center;">
                <a-statistic title="待退款" v-model="NoResponse"/>
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card :bordered="false" style="text-align: center;">
                <a-statistic title="待评价" v-model="Obligation"/>
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card :bordered="false" style="text-align: center;">
                <a-statistic title="待收货" v-model="WaitForReceiving"/>
              </a-card>
            </a-col>
          </a-row>
        </a-card>
        <a-card title="常用功能" class="dataCont-right">
          <a-row :gutter="16">
            <a-col :span="5">
              <a href="http://localhost:5051/#/goods/goods/goodsManage" class="function-item">
                <a-icon type="shopping-cart" style="color: #1890ff; font-size: 50px;"/>
                <div>发布商品</div>
              </a>
            </a-col>
            <a-col :span="5">
              <a href="http://localhost:5051/#/order/orderManage" class="function-item">
                <a-icon type="file-text" style="color: #ff4d4f; font-size: 50px;"/>
                <div>订单查询</div>
              </a>
            </a-col>
            <a-col :span="5">
              <a href="http://localhost:5051/#/marking/marking/coupon/couponManage" class="function-item">
                <a-icon type="gift" style="color: #faad14; font-size: 50px;"/>
                <div>优惠卷查询</div>
              </a>
            </a-col>
            <a-col :span="5">
              <a href="http://localhost:5051/#/user/userManage" class="function-item">
                <a-icon type="user" style="color: #52c41a; font-size: 50px;"/>
                <div>用户管理</div>
              </a>
            </a-col>
            <a-col :span="4">
              <a href="http://localhost:5051/#/CustomerService/CustomerServiceDepartment" class="function-item">
                <a-icon type="customer-service" style="color: #722ed1; font-size: 50px;"/>
                <div>客服咨询</div>
              </a>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <div style="background-color: white;margin-top: 20px;">
        <!-- 销售量趋势图 -->
        <div ref="orderNumChart" style="width: 100%; height: 420px;margin-top: 20px;"></div>
      </div>
    </template>
  </page-layout>
</template>

<script>

import PageLayout from '@/layouts/PageLayout';
import HeadInfo from '@/components/tool/HeadInfo';
// import Radar from '@/components/chart/Radar'
import {mapState} from 'vuex';
import {request, METHOD} from '@/utils/request';
import axios from "axios";

export default {
  name: 'WorkPlace',
  components: {HeadInfo, PageLayout},
  i18n: require('./i18n'),
  data() {
    return {
      GoodsWaitingToBeSent: 0,
      WaitForReceiving: 0,
      Obligation: 0,
      NoResponse: 0,
      PageView: 0,
      OrderNum: 0,
      QuantityOfCommodity: 0,
      total: 0,
      projects: [],
      loading: true,
      activities: [],
      teams: [],
      welcome: {
        timeFix: '',
        message: ''
      },
      OrderNumData: [9999, 23777, 89273, 81234, 9912, 66234, 0],
      timeLabels: ['七月', '八月', '九月', '十月', '十一月', '十二月', '一月'],
    };
  },
  computed: {
    ...mapState('account', {currUser: 'user'}),
    ...mapState('setting', ['lang'])
  },
  created() {
    request('/user/welcome', METHOD.GET).then((res) => (this.welcome = res.data));
    request('/work/activity', METHOD.GET).then((res) => (this.activities = res.data));
    request('/work/team', METHOD.GET).then((res) => (this.teams = res.data));
    request('/project', METHOD.GET).then((res) => {
      this.projects = res.data;
      this.loading = false;
    });
  },
  mounted() {
    this.initOrderNumChart();
    this.fetchOrderInfo();
    this.fetchOrderAfterInfo();
    this.fetchGoodData();
    // 从 localStorage 获取页面访问次数，如果没有则初始化为 0
    let savedPageView = localStorage.getItem('pageView');
    if (savedPageView === null) {
      this.pageView = 1000;  // 如果没有记录，初始化为 0
    } else {
      this.pageView = parseInt(savedPageView);  // 转换为数字
    }

    // 每次刷新时增加 1
    this.pageView++;

    // 更新 localStorage 存储的值
    localStorage.setItem('pageView', this.pageView);
    this.PageView = savedPageView;
  },
  methods: {
    loadECharts(callback) {
      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js';
      script.onload = callback;
      document.body.appendChild(script);
    },
    initOrderNumChart() {
      this.loadECharts(() => {
        const chartDom = this.$refs.orderNumChart;
        /* eslint-disable no-undef */
        const myChart = echarts.init(chartDom);

        const option = {
          title: {
            text: '销售金额趋势',
            left: 'center',
          },
          xAxis: {
            type: 'category',
            data: this.timeLabels,
          },
          yAxis: {
            type: 'value',
          },
          tooltip: {
            trigger: 'axis',
          },
          series: [
            {
              name: '销售金额',
              data: this.OrderNumData,
              type: 'bar',
              barWidth: '40%',
              itemStyle: {color: '#73C9E6'},
            },
          ],
        };

        myChart.setOption(option);
      });
    },
    // 获取订单信息
    async fetchOrderInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/order/infoidOrderAll`, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          const orderData = response.data.data;
          let orderMoney = 0;
          // 遍历订单数据，设置 username
          orderData.forEach(item => {
            item.username = item.username == null || item.username === "" ? "乐购" + (item.addressMobile ? item.addressMobile.slice(-4) : '') : item.username;
            orderMoney += item.money == null ? 0 : item.money;
          });
          this.OrderNum = orderData.length;
          this.GoodsWaitingToBeSent = orderData.filter(item => item.orderStatus === '待发货').length;
          this.WaitForReceiving = orderData.filter(item => item.orderStatus === '待收货').length;
          this.Obligation = orderData.filter(item => item.orderStatus === '已完成' && item.commentState === '未评价').length;
          this.OrderNumData[6] = orderMoney

          this.total = 0;  // 重置总和
          for (let num of this.OrderNumData) {
            this.total += num;  // 累加每个数
          }
          localStorage.setItem('OrderNum', orderData.length)
        } else {
          console.error('获取订单信息失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    async fetchOrderAfterInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/orderafter/infoorderafterall`, {
          headers: {Authorization: `Bearer ` + localStorage.getItem('token')}
        });
        if (response.data.code === 200) {
          let orderAfterData = response.data.data;
          // 遍历订单数据，设置 username
          orderAfterData.forEach(item => {
            item.username = item.username == null || item.username === "" ? "乐购" + (item.addressMobile ? item.addressMobile.slice(-4) : '') : item.username;
          });
          this.NoResponse = orderAfterData.filter(item => item.afterStatus === '售后中').length;
          this.filterData();
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    async fetchGoodData() {
      try {
        // 调用后端 API 获取用户信息
        const response = await request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/goods/infoAllGoods`,
            METHOD.GET
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        );
        const GoodsData = response.data.data;
        this.QuantityOfCommodity = GoodsData.length;
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>

<style scoped>
* {
  overflow: hidden;
}
</style>

<style lang="less">
@import "index";

.dataCont {
  max-width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  gap: 16px;
}

.dataCont-left,
.dataCont-right {
  flex: 1;
  height: 210px;
  color: white;
  padding: 16px;
  box-sizing: border-box;
}

.function-item {
  font-size: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.function-item div {
  color: black;
  margin-top: 10px;
}

.temperature {
  width: 100%;
  height: 350px;
}

</style>
